<!-- 行政区域划分 -->
<template>
  <div class="map-exchange-bg">
    <el-card class="map-bg">
      <div id="dividerMap"></div>
    </el-card>
    <div class="operate-bg">
      <el-card>
        <div slot="header" class="page-title-bg">
          <div class="page-title">
            <div class="title-icon"></div>
            <span>行政区域划分</span>
          </div>
        </div>
        <div class="divide-bg">
          <div class="divide-upload">
            <span>管辖区域：</span>
            <span>请上传机构下辖的行政区域表</span>
            <el-button type="primary" @click="downLoadFn()" size="mini" class="ml15">下载模板</el-button>
          </div>
          <el-form ref="rangeForm" v-model="rangeForm">
            <el-form-item>
              <el-upload
                ref="upload"
                class="upload-btn"
                action=""
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :file-list="fileList"
                :auto-upload="false">
                <el-button type="primary" size="small">上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item style="text-align: right;">
              <el-button size="mini" @click="uploadResetFn()">重置</el-button>
              <el-button type="primary" size="mini" @click="uploadSaveFn()" :disabled="fileList.length > 0">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-card style="margin-top: 20px;">
        <div slot="header" class="page-title-bg">
          <div class="page-title">
            <div class="title-icon"></div>
            <span>行政区域划分情况</span>
          </div>
        </div>
        <el-table :data="dividerList" style="width: 100%; height: calc(100vh - 480px);">
          <el-table-column prop="companyName" label="机构名称" align="center">
          </el-table-column>
          <el-table-column prop="companyCode" label="机构代码" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scoped">
              <el-button type="text" size="mini" @click="showComMap(scoped.row)">查看区域</el-button>
            <!-- </template>
            <template slot-scope="scoped"> -->
              <el-tooltip v-model="scoped.row.isShowSon" placement="bottom" effect="light" :manual="true">
                <el-button type="text" size="mini" @click="changeShowSon(scoped.$index)">区域分单</el-button>
                <!-- <el-button type="text" size="mini" @click="changeShowSon(scoped.$index)">{{scoped.row.companyName}}</el-button> -->
                <div slot="content" class="son-manage-com">
                  <div class="son-title">
                    <div>
                      <span>{{scoped.row.companyName}}</span>
                      <i class="el-icon-arrow-right"></i>
                      <span>三级机构</span>
                    </div>
                    <div>
                      <i class="el-icon-close" style="color: #082AFF; cursor: pointer;" @click="closeCheckDialog(scoped.$index)"></i>
                    </div>
                  </div>
                  <div class="son-com-list">
                    <el-checkbox-group v-model="scoped.row.checked" @change="checkChange($event, scoped.$index)">
                      <el-checkbox v-for="(item, index) in scoped.row.cityList" :label="item" :key="index">
                        {{item.label}}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <div style="text-align: right;">
                    <el-button type="primary" size="mini" :disabled="scoped.row.checked.length == 0" @click="rangeShareFn(scoped.row)">确定</el-button>
                  </div>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div style="float: right; margin: 20px 0;">
          <el-button size="mini">导出当前模板</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import LabelsData from "../china-pp";
import { getCompanyList } from '../../../api/renewalPlatformApi/index';

export default {
  name: '',
  data() {
    return {
      // 地图展示状态
      rangeForm: {
        manageCom: '无锡市',
        manageComCode: '320200',
        company: '',
      },
      fileList: [],
      dividerList: [],
      currentIsShowSonIdx: null,
      map: null,
    }
  },
  mounted() {
    this.mapLoad();
    this.getList();
    // this.mapExpandLoad();
  },
  methods: {
    // 重置
    uploadResetFn() {
      this.fileList = [];
    },
    // 提交
    uploadSaveFn() {
      this.$message.success("提交成功")
      this.getList();
    },
    getList() {
      getCompanyList({ companyType: '2' }).then((res) => {
        if (res.code === 200) {
          res.data.forEach(item => {
            let temp = {
              companyCode: item.companyCode,
              companyName: item.companyName,
              placeCode: item.placeCode,
              isShowSon: false,
              checked: [],
              cityList: []
            }
            this.dividerList.push(temp);
          });
        }
      }).finally(() => {})
    },
    // 地图初始化
    mapLoad() {
      let disCountry = new AMap.DistrictLayer.Country({
        zIndex: 10,
        SOC: 'CHN',
        depth:1,
        styles: {
          'nation-stroke':'#ff0000',
          'coastline-stroke':'#0088ff',
          'province-stroke':'grey',
        }
      })
      this.map = new AMap.Map("dividerMap",{
        zooms: [4.2, 8],
        center:[106.122082, 33.719192],
        zoom: 4.6,
        isHotspot: false,
        defaultCursor:'pointer',
        layers:[
          disCountry
        ],
        viewMode:'3D',
      })
      this.map.addControl(new AMap.Scale());
      this.map.addControl(new AMap.ToolBar({ liteStyle: true }));
      const _this = this;
      this.map.on('complete',function(){
        let layer = new AMap.LabelsLayer({
          // 开启标注避让，默认为开启，v1.4.15 新增属性
          collision: false,
          // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
          animation: true,
        });
        for (let i = 0; i < LabelsData.length; i++) {
          let labelsMarker = new AMap.LabelMarker(LabelsData[i]);
          layer.add(labelsMarker);
        }
        _this.map.add(layer);
      })
    },
    // 导入地图填色(二级机构)
    mapExpandLoad() {
      let excelList = [
        { adcode: "440000", name: "广东分公司" },
        { adcode: "320000", name: "江苏分公司" },
        { adcode: "330000", name: "浙江分公司" },
        { adcode: "110000", name: "北京分公司" },
        { adcode: "310000", name: "上海分公司" },
        { adcode: "410000", name: "河南分公司" },
        { adcode: "610000", name: "陕西分公司" },
      ];
      let currentData = LabelsData;
      let GDPSpeed = {};
      for (let i = 0; i < currentData.length; i++) {
        excelList.forEach(item => {
          if (item.adcode == currentData[i].adcode) {
            currentData[i].text.content = item.name;
          }
          GDPSpeed[item.adcode] = 1;
        });
      }
      console.log(currentData)
      let colors = {};
      let getColorByDGP = function(adcode){
        if(!colors[adcode]){
          let gdp = GDPSpeed[adcode];
          if(gdp){
            colors[adcode] = 'rgb(255, 120, 120)';
          } else {
            colors[adcode] = 'rgba(255, 255, 255)';
          }
        }
        return colors[adcode]
      }
      let disCountry = new AMap.DistrictLayer.Country({
        zIndex: 10,
        SOC: 'CHN',
        depth:1,
        styles: {
          'nation-stroke':'#ff0000',
          'coastline-stroke':'#0088ff',
          'province-stroke':'grey',
          'fill': function(props){
            return getColorByDGP(props.adcode_pro)
          }
        }
      })
      let map = new AMap.Map("dividerMap",{
        zooms: [4.2, 8],
        center:[106.122082,33.719192],
        zoom: 4.6,
        isHotspot: false,
        defaultCursor:'pointer',
        layers:[
          disCountry
        ],
        viewMode:'3D',
      })
      map.addControl(new AMap.Scale());
      map.addControl(new AMap.ToolBar({liteStyle:true}));
      map.on('complete',function(){
        let layer = new AMap.LabelsLayer({
          // 开启标注避让，默认为开启，v1.4.15 新增属性
          collision: false,
          // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
          animation: true,
        });
        for (let i = 0; i < currentData.length; i++) {
          let labelsMarker = new AMap.LabelMarker(currentData[i]);
          layer.add(labelsMarker);
        }
        map.add(layer);
      })
    },
    // 查看二级机构区域
    showComMap(row) {
      this.map = null;
      let adCode = row.placeCode + '';
      this.map = new AMap.Map("dividerMap", {
        center: [116.30946, 39.937629],
        zoom: 3
      });
      let polygons = [];
      //行政区划查询
      let opts = {
        subdistrict: 1,   // 返回下一级行政区
        showbiz: false  // 最后一级返回街道信息
      };
      let district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
      // 清除地图上所有覆盖物
      for (let i = 0, l = polygons.length; i < l; i++) {
        polygons[i].setMap(null);
      }
      district.setLevel('city'); // 行政区级别
      district.setExtensions('all');
      // 行政区查询：按照adcode进行查询可以保证数据返回的唯一性
      const _this = this;
      district.search(adCode, function (status, result) {
        if (status === 'complete') {
          let data = result.districtList[0];
          let bounds = data.boundaries;
          if (bounds) {
            for (let i = 0, l = bounds.length; i < l; i++) {
              let polygon = new AMap.Polygon({
                map: _this.map,
                strokeWeight: 1,
                strokeColor: '#0091ea',
                fillColor: '#80d8ff',
                fillOpacity: 0.2,
                path: bounds[i]
              });
              polygons.push(polygon);
            }
            _this.map.setFitView();//地图自适应
          }
        }
      });
    },
    // 导出模板
    downLoadFn() {
      this.mapExpandLoad();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    /** 选择三级机构 **/
    getCompanyListFn(index) {
      let code = this.dividerList[index].companyCode;
      getCompanyList({ companyType: '3', parentCode: code }).then((res) => {
        if (res.code === 200) {
          res.data.forEach(item => {
            let temp = {
              label: item.companyName,
              value: item.companyCode,
              placeCode: item.placeCode,
            }
            this.dividerList[index].cityList.push(temp);
          });
        }
      }).finally(() => { });
    },
    changeShowSon(index) {
      this.dividerList[index].cityList = []
      if (this.currentIsShowSonIdx != null) {
        if (this.currentIsShowSonIdx == index) {
          this.dividerList[index].isShowSon = false;
          this.currentIsShowSonIdx = null;
        } else {
          this.getCompanyListFn(index);
          this.dividerList[this.currentIsShowSonIdx].isShowSon = false;
          this.currentIsShowSonIdx = index;
          this.dividerList[index].isShowSon = true;
        }
      } else {
        this.getCompanyListFn(index);
        this.currentIsShowSonIdx = index;
        this.dividerList[index].isShowSon = true;
      }
    },
    checkChange(e, index) {
      if (this.dividerList[index].checked.length > 1) {
        let len = e.length - 1;
        this.dividerList[index].checked = [];
        this.dividerList[index].checked.push(e[len]);
      }
    },
    closeCheckDialog(index) {
      this.dividerList[index].isShowSon = false;
      this.dividerList[index].checked = [];
      this.currentIsShowSonIdx = null;
    },
    // 名单分配
    rangeShareFn(row) {
      console.log(row)
      let data = {
        companyCode: row.checked[0].value,
        companyName: row.checked[0].label,
        placeCode: row.checked[0].placeCode,
      }
      this.$emit('changeTab', '2', data);
    }
  }
}
</script>

<style lang="scss" scoped>
.map-exchange-bg{
  display: flex;
  .page-title-bg{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .page-title{
      display: flex;
      align-items: center;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #2A2A2A;
      .title-icon{
        width: 6px;
        height: 20px;
        background-color: #082AFF;
      }
      span{
        margin: 0 10px;
      }
    }
    .page-title-operate{
      padding-left: 10px;
    }
  }
  .map-bg{
    width: 60%;
    position: relative;
    ::v-deep.el-card__body{
      padding: 0;
    }
    #dividerMap{
      width: 100%;
      height: calc(100vh - 150px);
    }
  }
  .operate-bg{
    width: 39%;
    margin-left: 10px;
    .divide-bg{
      .divide-upload{
        padding: 0 0 10px 10px;
        span:nth-child(1){
          color: #818181;
        }
        span:nth-child(2){
          color: #CFCFCF;
        }
      }
      .upload-btn{
        display: inline-block;
      }
    }
  }
  ::v-deep.el-card__header {
    border: 0;
  }
  ::v-deep.el-card__body{
    padding: 15px;
  }
}
.son-manage-com{
  .son-title{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
    font-size: 14px;
    span:nth-child(1){
      color: gray;
    }
  }
  .son-com-list{
    width: 360px;
  }
}
</style>
